package com.example.test_witns;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.test_witns.adapter.message.MessagesAdapter;
import com.example.test_witns.databinding.FragmentChatBinding;
import com.example.test_witns.pojo.Message;
import com.example.test_witns.utils.MyInfosHelper;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMCustomElem;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.imsdk.v2.V2TIMTextElem;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class ChatActivity extends AppCompatActivity {
    private static final Logger log = LoggerFactory.getLogger(ChatActivity.class);
    private FragmentChatBinding binding;

    private MessagesAdapter messagesAdapter;

    private final LinearLayoutManager layoutManager = new LinearLayoutManager(this);

    private RecyclerView recyclerView;

    private List<Message> messages;
    private int message_counter = 0;

    String targetUserId;
    String targetNickname;
    String myNickname;
    byte[] targetAvatar;
    byte[] myAvatar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = FragmentChatBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //接收上页参数再加载
        Intent intent = getIntent();
        targetUserId = intent.getStringExtra("targetUserId");
        targetNickname = intent.getStringExtra("targetNickname");
        targetAvatar = intent.getByteArrayExtra("targetAvatar");
        loadHistoryMessages(targetUserId, 0, 0);

        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            /**
             * @param msg
             */
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
                String sender = msg.getSender();
                receiveMessage(targetAvatar, targetNickname, sender, parseMessageContent(msg));

                int totalItemCount = layoutManager.getItemCount();
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItem == totalItemCount - 1){
                    recyclerView.smoothScrollToPosition(messagesAdapter.getItemCount() - 1);
                }
            }

        });


        Objects.requireNonNull(getSupportActionBar()).hide();

        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        window.setStatusBarColor(Color.parseColor("#dddddd"));

        View chatBackToDevice = findViewById(R.id.chat_backToDevices);
        chatBackToDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                V2TIMManager.getMessageManager().markC2CMessageAsRead(targetUserId, new V2TIMCallback() {
                    @Override
                    public void onSuccess() {
                        Log.d(TAG, "onSuccess:" + "清除完成");
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
                finish();
            }
        });

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                V2TIMManager.getMessageManager().markC2CMessageAsRead(targetUserId, new V2TIMCallback() {
                    @Override
                    public void onSuccess() {
                        Log.d(TAG, "onSuccess:" + "清除完成");

                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
                finish();
            }
        });

        recyclerView = findViewById(R.id.recycler_view_messages);
        recyclerView.setLayoutManager(layoutManager);

        messages = new ArrayList<>();
        messagesAdapter = new MessagesAdapter(messages);
        recyclerView.setAdapter(messagesAdapter);

        TextView sessionName = findViewById(R.id.msg_header_sessionName);
        sessionName.setText(targetNickname);

        EditText editText = findViewById(R.id.edit_text_message);
        ImageButton imageButton = findViewById(R.id.image_button_send);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().toString().trim().isEmpty()){
                    return;
                }
                sendMessage(myAvatar, myNickname, targetUserId, editText.getText().toString());
                editText.setText("");
            }
        });

        MyInfosHelper myInfosHelper = new MyInfosHelper(ChatActivity.this);
        boolean isLogin = myInfosHelper.checkIfLogin();
        if (isLogin && !BottomNavigationViewActivity.onLogin){
            V2TIMSDKConfig config = new V2TIMSDKConfig();
            config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
            V2TIMManager.getInstance().initSDK(ChatActivity.this,1600066337, config);

            myInfosHelper.loadMyInfos(new MyInfosHelper.GetMyInfos() {
                @Override
                public void onLoadingMyInfos(String email, String sig, String name, String uuid, byte[] avatar, String uri, String url) {
                    V2TIMManager.getInstance().login(email, sig, new V2TIMCallback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onError(int i, String s) {
                            Toast.makeText(ChatActivity.this, "登录过期", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }else if (isLogin && BottomNavigationViewActivity.onLogin){

        }else {
            Toast.makeText(this, "您尚未登录", Toast.LENGTH_SHORT).show();
        }

    }

    public void sendMessage(byte[] myAvatar, String myNickname, String receiver, String text){
        String timestamp = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
        Message message = new Message(myAvatar, myNickname, receiver, text, timestamp, true);
        messagesAdapter.addMessage(message);
        recyclerView.smoothScrollToPosition(messagesAdapter.getItemCount() - 1);

        EditText edit_text_message = findViewById(R.id.edit_text_message);
        String messageContent = edit_text_message.getText().toString();

        V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createTextMessage(messageContent);

        V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, targetUserId, null, V2TIMMessage.V2TIM_PRIORITY_NORMAL, false, null, new V2TIMSendCallback<V2TIMMessage>() {
            @Override
            public void onProgress(int i) {
                Toast.makeText(ChatActivity.this, "发送中", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                Toast.makeText(ChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(ChatActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void receiveMessage(byte[] senderAvatar, String senderNickname, String sender, String text){
        String timestamp = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
        Message message = new Message(senderAvatar, senderNickname, sender, text, timestamp, false);
        messagesAdapter.addMessage(message);
    }

    public void loadHistoryMessages(String userId, int pageSize, int startIndex) {
        V2TIMManager.getMessageManager().getC2CHistoryMessageList(userId, 20, null, new V2TIMValueCallback<List<V2TIMMessage>>() {
            @Override
            public void onSuccess(List<V2TIMMessage> v2TIMMessages) {
                MyInfosHelper myInfosHelper = new MyInfosHelper(ChatActivity.this);
                String myUserId = myInfosHelper.getMyUserId();
                myNickname = myInfosHelper.getMyNickname();
                myAvatar = myInfosHelper.getAvatarByName(myInfosHelper.getMyUserId());

                v2TIMMessages.forEach(v2TIMMessage -> {
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
                    linearLayoutManager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(linearLayoutManager);
                    recyclerView.setHasFixedSize(true);

                    if (v2TIMMessage.getElemType() == V2TIMMessage.V2TIM_ELEM_TYPE_TEXT){
                        V2TIMTextElem textElem = v2TIMMessage.getTextElem();
                        long timestamp = v2TIMMessage.getTimestamp();
                        long currentTimestamp = System.currentTimeMillis();
                        String formattedDateTime = null;
                        DateTimeFormatter dateTimeFormatter;
                        LocalDate currentDate = LocalDate.now();
                        LocalDate messageDate = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault()).toLocalDate();
                        LocalDateTime messageDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
                        if (v2TIMMessage.getSender().equals(myUserId)){
                            if (currentDate.equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = messageDateTime.format(dateTimeFormatter);
                            }else if(currentDate.minusDays(1).equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = "昨天 " + messageDateTime.format(dateTimeFormatter);
                            }else if (currentDate.minusDays(2).equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = "前天 " + messageDateTime.format(dateTimeFormatter);
                            }else {
                                dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd HH:mm");
                                formattedDateTime = messageDateTime.format(dateTimeFormatter);
                            }
                            Message message = new Message(myAvatar, myNickname, myUserId, textElem.getText(), formattedDateTime, true);
                            messagesAdapter.addMessageReverse(message);
                        }else {
                            if (currentDate.equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = messageDateTime.format(dateTimeFormatter);
                            }else if(currentDate.minusDays(1).equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = "昨天 " + messageDateTime.format(dateTimeFormatter);
                            }else if (currentDate.minusDays(2).equals(messageDate)){
                                dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
                                formattedDateTime = "前天 " + messageDateTime.format(dateTimeFormatter);
                            }else {
                                dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd HH:mm");
                                formattedDateTime = messageDateTime.format(dateTimeFormatter);
                            }
                            Message message = new Message(targetAvatar, targetNickname, targetUserId, textElem.getText(), formattedDateTime, false);
                            messagesAdapter.addMessageReverse(message);
                        }
                    }
                });

            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    private String parseMessageContent(V2TIMMessage msg) {
        if (msg.getElemType() == V2TIMMessage.V2TIM_ELEM_TYPE_TEXT) {
            // 文本消息
            V2TIMTextElem textElem = msg.getTextElem();
            return textElem.getText();
            // 处理文本消息内容
        } else if (msg.getElemType() == V2TIMMessage.V2TIM_ELEM_TYPE_CUSTOM) {
            // 自定义消息
            V2TIMCustomElem customElem = msg.getCustomElem();
            // 处理自定义消息内容
        }
        // 处理其他类型的消息...
        return null;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }
}


//        // Your unique Azure Communication service endpoint
//        String endpoint = "https://chat-service-witns.unitedstates.communication.azure.com/";
//
//        // User access token fetched from your trusted service
//        String userAccessToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjExRkNCRjhEQzBFRTMzQUY3QkIwQTE3OUUzNjI0RUNBNjk1ODE2NjQiLCJ4NXQiOiJFZnlfamNEdU02OTdzS0Y1NDJKT3ltbFlGbVEiLCJ0eXAiOiJKV1QifQ.eyJza3lwZWlkIjoiYWNzOmUwZWQyYjU5LWI5ZDMtNGM5Yi1iZmRlLWQ2NzRiZGIxZTg0Nl8wMDAwMDAyNC02NTVjLTU1N2QtMTAwMC0zNDNhMGQwMGQwZmIiLCJzY3AiOjE3OTIsImNzaSI6IjE3MzQxODQ5NzIiLCJleHAiOjE3MzQyNzEzNzIsInJnbiI6ImFtZXIiLCJhY3NTY29wZSI6ImNoYXQiLCJyZXNvdXJjZUlkIjoiZTBlZDJiNTktYjlkMy00YzliLWJmZGUtZDY3NGJkYjFlODQ2IiwicmVzb3VyY2VMb2NhdGlvbiI6InVuaXRlZHN0YXRlcyIsImlhdCI6MTczNDE4NDk3Mn0.SzKMzUYhJGLMclBWpIminDYQaawKR1bB5w3Dv4mtfgiyCqTb9-Czz80-CwvVUxXnAZpmYJ1_PbonxyOXiDF-5-zKIQ2kVV3YDc3Yb2_y4TL7nDPutxFdEh1FDMzhkXm7tAVabngbo_GWFBCu94-kASrYcsbS16gayRWGLedMmtigOfWZujTAzPPsz-oIhOI_ZRqYz-AhJb98AChV_3Y3HCURRLtUyff1CVHl2Zc0OOtaVdFjcNdpZMxjwTv5WL3uaRVhVMQ5c9DNpvWT-SXbmKvBJfNpOEXzsAO_zzoFPQcmFin5Pcm_dWWM49x5oplrAmky8fMj7DPC13xGVEmDEw";
//
//        // Create a CommunicationTokenCredential with the given access token, which is only valid until the token is valid
//        CommunicationTokenCredential userCredential = new CommunicationTokenCredential(userAccessToken);
//
//        // Initialize the chat client
//        final ChatClientBuilder builder = new ChatClientBuilder();
//        builder.endpoint(endpoint)
//                .credential(userCredential);
//        ChatClient chatClient = builder.buildClient();
//
//        CommunicationUserIdentifier identity1 = new CommunicationUserIdentifier("111");
//        CommunicationUserIdentifier identity2 = new CommunicationUserIdentifier("222");
//
//        ChatParticipant firstThreadParticipant = new ChatParticipant()
//                .setCommunicationIdentifier(identity1)
//                .setDisplayName("Participant Display Name 1");
//
//        ChatParticipant secondThreadParticipant = new ChatParticipant()
//                .setCommunicationIdentifier(identity2)
//                .setDisplayName("Participant Display Name 2");
//        List<ChatParticipant> list = new ArrayList<>();
//        list.add(firstThreadParticipant);
//        list.add(secondThreadParticipant);
//
//        CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
//                .setTopic("Topic")
//                .setParticipants(list);
//
//        if(createChatThreadOptions.getParticipants() == null){
//            sendMessage("user", "null list");
//            editText.setText("");
//        }
//
//        if(createChatThreadOptions.getParticipants() == null){
//            sendMessage("user", "null list");
//            editText.setText("");
//        }

//        chatClient.createChatThread(createChatThreadOptions);
//
//        CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
//        String chatThreadId = result.getChatThreadProperties().getId();
//
//        SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
//                .setContent("你好，这是一条消息")
//                .setType(com.azure.android.communication.chat.models.ChatMessageType.TEXT)
//                .setSenderDisplayName("发送者的显示名称");
//
//        SendChatMessageResult sendMessageResult = chatClient.getChatThreadClient(chatThreadId).sendMessage(sendChatMessageOptions);
